package com.compress

import kotlin.io.path.*
import kotlin.math.ceil

class Main(arrStr: String) {

    private var index: Int
    private val paths: List<String>
    private val consolePro = ConsoleProgressBar(0, 100, 30)

    init {
        consolePro.startChar = "%n% "
        paths = arrStr.split(",")
        index = 0
        nextCompress()
    }

    /**
     * 开始压缩下一个
     */
    private fun nextCompress() {
        val path = paths[index]
        quality = if (quality.isNullOrBlank()) "80" else quality
        PicUtils.commpressPic(path, quality!!)
        index++
        val pro = index.toDouble() / paths.size
        val p = ceil(pro * 100).toInt()

//        consolePro.details = "还剩下 = " + (paths.length - index) + "!";
        consolePro.details = ""
        consolePro.show(p)
        if (paths.size > index) {
            nextCompress()
        }
    }

    companion object {
        private var quality: String? = null

        @JvmStatic
        fun main(args: Array<String>) {
            if (args.size == 2) {
                quality = args[0] // 压缩质量
                var source = args[1] // 压缩文件路径
                if (source.isBlank()) {
                    System.err.println("文件路径是null")
                    return
                }

                // 判断是否是路径
                if (!source.contains(",")) {
                    val file = Path(source)
                    if (file.exists()) {
                        try {
                            if (file.isDirectory()) {
                                System.err.println("不能传入文件夹")
                                return
                                //                            System.out.println("传入文件夹");
//                            source = FileUtils.readFileToString(file, Charset.defaultCharset());
                            } else {
                                if (file.extension == "txt") {
                                    println("传入配置文件")
                                    source = file.readText()
                                } else {
                                    println("传入文件")
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                            return
                        }
                    } else {
                        System.err.println("执行文件路径不正确：$source")
                        return
                    }
                }
                Main(source)
                println("\n")
                println("图片压缩完成！")
            } else {
                System.err.println("压缩命令错误！")
            }
        }
    }

}
